package groovy.lang.webobjects;

import java.lang.reflect.Field;

import com.webobjects.foundation.NSDictionary;
import com.webobjects.foundation._NSThreadsafeMutableDictionary;
import com.webobjects.foundation._NSUtilities;

public class WOGroovyClassCache {
	private static boolean initialized = false;
	private static _NSThreadsafeMutableDictionary classesByPartialName = null;
	
	public static void setClassForName(Object objectClass, Object className) {
		classesByPartialName.setObjectForKey(objectClass, className);
	}
	
	public static void removeClassForName(Object className) {
		classesByPartialName.removeObjectForKey(className);
	}
	
	public static Class<?> classForName(String className) {
        return _NSUtilities.classWithName(className);
	}
	
	@SuppressWarnings("unchecked")
	public static NSDictionary<String, Class<?>> getClassCache() {
		return classesByPartialName.immutableClone();
	}
	
	@SuppressWarnings("unchecked")
	private static void initialize() {
		if (initialized) return;
		initialized = true;
		try {
			Field f = _NSUtilities.class.getDeclaredField("_classesByPartialName");
			f.setAccessible(true);
			classesByPartialName = (_NSThreadsafeMutableDictionary)f.get(null);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	static {
		initialize();
	}
}
